﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FySystem.IO
{
    public class ImgIO
    {
        /// <summary>
        /// 保存图片到指定目录
        /// </summary>
        /// <param name="v"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        public static string SaveBase64Img(string fileName, string img)
        {
            string res = "";
            try
            {
                byte[] byteData = Base64ImgToBytes(img);

                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(byteData, 0, byteData.Length);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// base64转字节数组
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static byte[] Base64ImgToBytes(string base64Str)
        {
            byte[] res = new byte[0];
            try
            {
                //去掉base64字符串的头部信息（格式：...）
                int index = -1;
                index = base64Str.IndexOf(',');
                if (index > -1)
                    base64Str = base64Str.Substring(index + 1);

                res = Convert.FromBase64String(base64Str);
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }
    }
}
